package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;
    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery query) {
        log.debug("query:{}",query);
        List<VehicleVO> list=vehicleMapper.selectVehicle(query);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam param) {
        log.debug("param:{}",param);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(param,vehicle);
        //判断车牌号是否存在
        VehicleVO vehicleVO =vehicleMapper.selectVehicleByLicense(vehicle.getLicense());
        if(vehicle.getId()==null){
            if(vehicleVO != null){
                throw new ServiceException(StatusCode.LICENSE_EXISTS);
            }
            vehicle.setStatus("1");
            vehicle.setGeofenceBindStatus("0");
            vehicle.setCreateTime(new Date());
            vehicleMapper.insert(vehicle);
        }else{
            //如果车牌号已存在,且不是本辆车的车牌号(与其它已存在的车牌号重复)
            if(vehicleVO != null && vehicleVO.getId() != vehicle.getId()){
                throw new ServiceException(StatusCode.LICENSE_EXISTS);
            }
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void deleteVehicle(Long id) {
        log.debug("id:{}",id);
        vehicleMapper.deleteById(id);
    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("解绑车辆业务,参数={}",vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateNullValue(vehicle);
    }

    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setGeofenceId(geofenceId);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
